import csv
from django.http import HttpResponse
# followviews.py
from django.shortcuts import render
from django.http import JsonResponse
from django.core.paginator import Paginator
from django.utils import timezone
from app.models import SkuKeywords, FollowPrice
import pandas as pd
import json
from django.views.decorators.csrf import csrf_exempt

def followprice_view(request):
    if request.method == 'POST':
        action = request.POST.get('action')
        if action == 'query':
            sku = request.POST.get('sku')
            keywords = request.POST.get('keywords')
            chargeman = request.POST.get('chargeman')
            ebay = request.POST.get('ebay') == 'on'
            ali = request.POST.get('ali') == 'on'
            lista = SkuKeywords.objects.filter(sku__icontains=sku,
                                               keywords__icontains=keywords,
                                               chargeman__icontains=chargeman,
                                               ebay=ebay,
                                               ali=ali)
            paginator = Paginator(lista, 20)
            page_number = request.GET.get('page')
            page_obj = paginator.get_page(page_number)
            return render(request, 'followprice2.html', {'lista': page_obj})
        elif action == 'follow':
            selected_ids = request.POST.getlist('selected_ids')
            for sku_obj in SkuKeywords.objects.filter(id__in=selected_ids):
                FollowPrice.objects.create(
                    shop_type='ebay' if sku_obj.ebay else 'ali',
                    storename=
                    'Your Store Name',  # replace with actual store name
                    keywords=sku_obj.keywords,
                    titile='Title',  # replace with actual title
                    link='Link',  # replace with actual link
                    pic='Pic',  # replace with actual pic
                    price='Price',  # replace with actual price
                    salesvolume=0,  # replace with actual sales volume
                    salesvolume2=0,  # replace with actual sales volume2
                    pic2='Pic2',  # replace with actual pic2
                    price2='Price2',  # replace with actual price2
                    itemid=sku_obj.sku,
                    lowvalue=sku_obj.lowvalue,
                    opdate=timezone.now(),
                    username=request.user.
                    username  # replace with actual username
                )
            return JsonResponse({'status': 'success'})
        elif action == 'unfollow':
            selected_ids = request.POST.getlist('selected_ids')
            FollowPrice.objects.filter(itemid__in=selected_ids).delete()
            return JsonResponse({'status': 'success'})
        elif action == 'export':
            listb = FollowPrice.objects.all()
            df = pd.DataFrame(list(listb.values()))
            response = HttpResponse(content_type='application/vnd.ms-excel')
            response[
                'Content-Disposition'] = 'attachment; filename="followprice.xlsx"'
            df.to_excel(response, index=False)
            return response
    elif request.method == 'GET':
        listb = FollowPrice.objects.all()
        paginator = Paginator(listb, 20)
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)
        return render(request, 'followprice.html', {'listb': page_obj})

@csrf_exempt
def sku_follow_view(request, modelid):
    if modelid ==0 :
        sku_keywords_view(request)
    elif modelid==1 :
        sku_followprice_view(request)
            

      

@csrf_exempt

def sku_keywords_view(request):
    """
    处理SkuKeywords数据查询请求的视图函数
    """
    page_size = 20  # 每页记录数

    if request.method == 'POST':
        try:
            form_data = json.loads(request.body)  # 解析POST请求中的JSON数据
            sku = form_data.get('sku', '')
            keywords = form_data.get('keywords', '')
            chargeman = form_data.get('chargeman', '')

            queryset = SkuKeywords.objects.all()
            if sku:
                queryset = queryset.filter(sku__icontains=sku)
            if keywords:
                queryset = queryset.filter(keywords__icontains=keywords)
            if chargeman:
                queryset = queryset.filter(chargeman__icontains=chargeman)

            paginator = Paginator(queryset, page_size)
            page_number = form_data.get('page', 1)
            page_obj = paginator.get_page(page_number)

            result = []
            for item in page_obj:
                result_dict = {
                    'id': item.id,
                    'sku': item.sku,
                    'keywords': item.keywords,
                    'chargeman': item.chargeman,
                    'lowvalue': item.lowvalue,
                    'ebay': item.ebay,
                    'ali': item.ali
                }
                result.append(result_dict)

            return JsonResponse({'status': 'success', 'data': result})
        except:
            return JsonResponse({
                'status': 'error',
                'error_message': '查询出现问题'
            },
                                status=500)


def sku_followprice_view(request):
    """
    处理SkuKeywords数据查询请求的视图函数
    """
    page_size = 20  # 每页记录数

    if request.method == 'POST':
        try:
            form_data = json.loads(request.body)  # 解析POST请求中的JSON数据
            sku = form_data.get('sku', '')
            keywords = form_data.get('keywords', '')
            chargeman = form_data.get('chargeman', '')

            queryset = SkuKeywords.objects.all()
            if sku:
                queryset = queryset.filter(sku__icontains=sku)
            if keywords:
                queryset = queryset.filter(keywords__icontains=keywords)
            if chargeman:
                queryset = queryset.filter(chargeman__icontains=chargeman)

            paginator = Paginator(queryset, page_size)
            page_number = form_data.get('page', 1)
            page_obj = paginator.get_page(page_number)

            result = []
            for item in page_obj:
                result_dict = {
                    'id': item.id,
                    'sku': item.sku,
                    'keywords': item.keywords,
                    'chargeman': item.chargeman,
                    'lowvalue': item.lowvalue,
                    'ebay': item.ebay,
                    'ali': item.ali
                }
                result.append(result_dict)

            return JsonResponse({'status': 'success', 'data': result})
        except:
            return JsonResponse({
                'status': 'error',
                'error_message': '查询出现问题'
            },
                                status=500)
